package org.opu.vcforms.template.bean;

import java.util.Collection;
import org.opu.doc2db.document.datadocument.ParagraphList;
import org.opu.doc2db.document.datadocument.TableCell;
import org.opu.doc2db.document.datadocument.TableRow;
import org.simpleframework.xml.Root;

/**
 *  Warning input data must be only TableRow or Contents
 * @author yura
 */
@Root(name="table")
public class SmartTable extends ParagraphList<ParagraphList> {

    public SmartTable() {
        super.dataSeparator = "\n";
    }

    public SmartTable(Collection<ParagraphList> rows) {
        super(rows);
        super.dataSeparator = "\n";
    }

    /**
     *  Add empty row to the end of rows list
     *
     * @return true if rows list changed as a result of the call
     */
    public boolean rowsAddEmpty() {
        return elementsAdd(new TableRow());
    }

    /**
     *  Add cell into end of last row
     *
     * @param cell cell the will be add
     * @return true if rows list changed as a result of the call
     */
    public boolean addInEnd(TableCell cell) {
        int size = elements.size();
        TableRow r = (TableRow) elements.get(size);

        return r.elementsAdd(cell);
    }

    /**
     * @see ParagraphList#elementsAdd(org.opu.doc2db.document.datadocument.Paragraph) 
     * @throws IllegalArgumentException if  paragraphList not
     * instanceof {@link Content} or {@link TableRow}
     */
    @Override
    public boolean elementsAdd(ParagraphList paragraphList)
            throws IllegalArgumentException {

        check(paragraphList);
        return super.elementsAdd(paragraphList);
    }

    /**
     * @see ParagraphList#elementsAdd(org.opu.doc2db.document.datadocument.Paragraph)
     * @throws IllegalArgumentException if  paragraphList not
     * instanceof {@link Content} or {@link TableRow}
     */
    @Override
    public boolean elementsAddAll(Collection<? extends ParagraphList> c)
            throws IllegalArgumentException {

        for (ParagraphList pl : c) {
            check(pl);
        }
        return super.elementsAddAll(c);
    }

    /**
     *  If paragraphList not instanceof {@link Content} or
     * {@link TableRow} fire {@link IllegalArgumentException}
     *
     * @param paragraphList 
     * @throws IllegalArgumentException if  paragraphList not
     * instanceof {@link Content} or {@link TableRow}
     */
    protected void check(ParagraphList paragraphList)
            throws IllegalArgumentException {

        if (!(paragraphList instanceof Content
                || paragraphList instanceof TableRow)) {

            throw new IllegalArgumentException("SmartTable can have only "
                    + "org.opu.vcforms.template.bean.Content or "
                    + "org.opu.doc2db.document.datadocumen.TableRow");
        }
    }
}
